package com.gitee.wsl.jvm.reflect.autobox

import com.gitee.wsl.jvm.exception.JobRunrException.Companion.shouldNotHappenException
import com.gitee.wsl.jvm.reflect.ReflectionUtils.cast
import java.sql.Clob
import java.sql.SQLException

class StringTypeAutoboxer : TypeAutoboxer<String> {
    override fun supports(type: Class<*>): Boolean {
        return String::class.java == type
    }

    override fun autobox(value: Any, type: Class<String>): String {
        if (value is String) {
            return value
        } else if (value is Clob) {
            try {
                val clob = value
                return cast(clob.getSubString(1, clob.length().toInt()))
            } catch (e: SQLException) {
                throw shouldNotHappenException(e)
            }
        }
        throw UnsupportedOperationException(
            String.format(
                "Cannot autobox %s of type %s to %s",
                value,
                value.javaClass.name,
                String::class.java.name
            )
        )
    }
}
